package com.sara.shiro;

import com.sara.entity.Permission;
import com.sara.service.PermissionService;
import org.apache.shiro.config.Ini;
import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
import org.apache.shiro.web.servlet.AbstractShiroFilter;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @author Wayne
 * @date 2019/1/21
 */
public class MyFilterChainDefinition {

    @Autowired
    private PermissionService permissionService;

    private AbstractShiroFilter shiroFilter;

    private  String filterChainDefinitions;


    public void setFilterChainDefinitions(String filterChainDefinitions){
        this.filterChainDefinitions = filterChainDefinitions;
    }

    public void setShiroFilter(AbstractShiroFilter shiroFilter){
        System.out.println("注入shiro");
        this.shiroFilter = shiroFilter;
    }


    @PostConstruct
    public void init(){
        System.out.println("权限初始化中...............");
        getFilterChainManager().getFilterChains().clear();
        load();
    }

    public void update(){
        System.out.println("------------权限更新中-----------");
        getFilterChainManager().getFilterChains().clear();
        load();
    }

    private DefaultFilterChainManager getFilterChainManager(){
        PathMatchingFilterChainResolver pathMatchingFilterChainResolver = (PathMatchingFilterChainResolver) this.shiroFilter.getFilterChainResolver();
        DefaultFilterChainManager defaultFilterChainManager = (DefaultFilterChainManager) pathMatchingFilterChainResolver.getFilterChainManager();
        return defaultFilterChainManager;
    }

    public void load(){
        Ini ini = new Ini();
        ini.load(filterChainDefinitions);
        Ini.Section section = ini.getSection(Ini.DEFAULT_SECTION_NAME);
        List<Permission> permissions = permissionService.findAllPermission();
        for(Permission permission : permissions){
            section.put(permission.getUrl(), "perms[" + permission.getPermissionCode() + "]");
        }
        DefaultFilterChainManager defaultFilterChainManager = getFilterChainManager();
        for(Ini.Section.Entry<String,String> entry : section.entrySet()){
            defaultFilterChainManager.createChain(entry.getKey(), entry.getValue());
        }
    }
}
